﻿CREATE PROCEDURE [dbo].[vk_AddPartner]
	@personId NVARCHAR(128),
	@partnerId NVARCHAR(128)
AS
BEGIN
	SET @personId = LTRIM(RTRIM(LOWER(@personId)))
	SET @partnerId = LTRIM(RTRIM(LOWER(@partnerId)))
	
	IF NOT EXISTS (SELECT * FROM [dbo].[vk_Relations] WHERE [UserId] = @personId AND [PartnerId] = @partnerId AND [Complete] = 0)
	BEGIN
		INSERT INTO [dbo].[vk_Relations]
							 ([UserId]
							 ,[PartnerId])
			 VALUES
						 (@personId
						 ,@partnerId)
	END
	
	IF EXISTS (SELECT * FROM [dbo].[vk_Relations] WHERE [UserId] = @partnerId AND [PartnerId] = @personId AND [Complete] = 0)
	BEGIN
		BEGIN TRY
			BEGIN TRAN

			UPDATE [dbo].[vk_Relations]
			SET [Complete] = 1
					,[CompleteDate] = GETUTCDATE()
			WHERE [UserId] = @partnerId AND [PartnerId] = @personId AND [Complete] = 0

			UPDATE [dbo].[vk_Relations]
			SET [Complete] = 1
					,[CompleteDate] = GETUTCDATE()
			WHERE [UserId] = @personId AND [PartnerId] = @partnerId AND [Complete] = 0

			COMMIT TRAN
		END TRY
		BEGIN CATCH
			ROLLBACK TRAN
		END CATCH

		SELECT CAST(1 AS BIT) AS 'Bingo'
	END
	ELSE
	BEGIN
		SELECT CAST(0 AS BIT) AS 'Bingo'
	END

END